package com.logos.ruralrevitalization.controller;

import com.logos.ruralrevitalization.result.Result;
import com.logos.ruralrevitalization.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {

    @Resource
    private AliOssUtil aliOssUtil;

    /**
     * 阿里云文件上传
     *
     */
    @PostMapping("/ali/upload")
    public Result<String> upload(MultipartFile uploadFile) {
        log.info("开始文件上传：{}", uploadFile);
        try {
            // 获取原始文件名
            String originalFilename = uploadFile.getOriginalFilename();
            // 获取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 得到新的文件名
            String freshFileName = UUID.randomUUID().toString() + extension;
            // 文件的请求路径
            String filePath = aliOssUtil.upload(uploadFile.getBytes(), freshFileName);
            return Result.ok(filePath);
        } catch (Exception e) {
            log.error("FileController.upload.aiOss.fail：{}", e.getMessage(),e);
            return Result.fail("上传文件失败");
        }
    }

}
